﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;

namespace Mvc.XForms.Utilities {
	public static class EnumHelper {
		public static bool TryGetEnumList<TEnum>(out IList<TEnum> enumList) {
			var enumType = typeof(TEnum);
			enumList = new List<TEnum>();

			if (!enumType.IsEnum) {
				if (!enumType.IsGenericType)
					return false;

				if (!enumType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
					return false;

				enumType = new NullableConverter(enumType).UnderlyingType;
			}

			enumList = Enum.GetValues(enumType).OfType<TEnum>().ToList();
			return true;
		}

		public static IList<TEnum> GetEnumList<TEnum>() {
			IList<TEnum> enumList;
			if (!TryGetEnumList<TEnum>(out enumList))
				throw new InvalidOperationException(string.Format("Type \"{0}\" cannot be converted to an enum list", typeof(TEnum)));

			return enumList;
		}
	}
}